﻿using Asxsyd92Core.Utils;
using WebOS.Modle;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace WebOSCore.Models
{
    public class ConnectionList : IReadOnlyCollection<OnlineUser>
    {
        /// <summary>
        /// 在线连接的集合
        /// </summary>
        private readonly ConcurrentDictionary<Guid, OnlineUser> _connections = new ConcurrentDictionary<Guid, OnlineUser>();
        /// <summary>
        /// 用户Id对应的用户对象
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        public OnlineUser this[Guid userId]
        {
            get
            {
                if (_connections.TryGetValue(userId, out var connection))
                {
                    return connection;
                }
                return null;
            }
        }
        /// <summary>
        /// 连接数量
        /// </summary>
        public int Count => _connections.Count;
        /// <summary>
        /// 加入用户
        /// </summary>
        /// <param name="user">用户对象</param>
        public void Add(OnlineUser user)
        {
            _connections.TryAdd(user.id.ToGuid(), user);
        }
        /// <summary>
        /// 移除用户
        /// </summary>
        /// <param name="userId">用户Id</param>
        public void Remove(Guid userId)
        {
            _connections.TryRemove(userId, out var dummy);
        }
        /// <summary>
        /// 实现接口
        /// </summary>
        /// <returns></returns>
        public IEnumerator<OnlineUser> GetEnumerator()
        {
            foreach (var item in _connections)
            {
                yield return item.Value;
            }
        }
        /// <summary>
        /// 实现接口
        /// </summary>
        /// <returns></returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }


    }
    [Authorize]
    public class ChatRoom : Hub
    {
        private ConnectionList Connections
        {
            get
            {
                return Context.GetHttpContext().RequestServices.GetService(typeof(ConnectionList)) as ConnectionList;
            }
        }
        private OnlineUser SessionManager
        {
            get
            {
                OnlineUser os = new OnlineUser();
                os.id = Context.User.Claims.FirstOrDefault(c => c.Type == "id").Value;
                os.username= Context.User.Claims.FirstOrDefault(c => c.Type == "name").Value;
                os.ConnectionId = Context.ConnectionId;
                //os.sign = Context.User.Claims.FirstOrDefault(c => c.Type == "sign").Value;
                //os.avatar = Context.User.Claims.FirstOrDefault(c => c.Type == "avatar").Value;
                return os;
              // return Context.User.Claims.ToList() as OnlineUser;
            //   return Context.GetHttpContext().RequestServices.GetService(typeof(OnlineUser)) as OnlineUser;

            }
        }
        /// <summary>
        /// 客户端连接时触发
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            var currUser = SessionManager;
            Connections.Add(currUser);
            //发送在线人数给当前客户端
            await Clients.Caller.SendAsync("OnlineCount", Connections.Count);
            //通知其他客户端有人上线
            await Clients.Others.SendAsync("UserOnline", currUser.username);
        }
        /// <summary>
        /// 客户端断开连接时触发
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception ex)
        {
            var currUser = SessionManager;
            Connections.Remove(currUser.id.ToGuid());
            //通知其他客户端有人下线
            await Clients.Others.SendAsync("UserOffline", currUser.username);
        }
        /// <summary>
        /// 客户端发送消息
        /// </summary>
        /// <param name="message"></param>
        public void Send(string message)
        {
            if (string.IsNullOrEmpty(message))
                return;
            var currUser = SessionManager;
            //发送给除自己以外的所有客户端
            Clients.Others.SendAsync("Receive", new { Msg = message, UserAvatar = currUser.avatar, UserName = currUser.username, Mine = false });
        }
        /// <summary>
        /// 客户端发送私聊消息
        /// </summary>
        /// <param name="message"></param>
        public void SendByUser(string userid,string message)
        {
            if (string.IsNullOrEmpty(message))
                return;
    
             var currUser = Connections.FirstOrDefault(c=>c.id==userid);
            //发送给除自己以外的所有客户端
            Clients.Client(currUser.ConnectionId).SendAsync("Receive", new { Msg = message, UserAvatar = currUser.avatar, UserName = currUser.username, Mine = false });
        }
    }
}

 class OnlineUser
{
    /// <summary>
    /// 连接ID
    /// </summary>
    public string ConnectionId { get; set; }
    /// <summary>
    /// 用户ID
    /// </summary>


    public string username { get; set; }
    /// <summary>
    /// 
    /// </summary>

    public Guid id { get; set; }
    /// <summary>
    /// 
    /// </summary>

    public string avatar { get; set; }
    /// <summary>
    /// 这些都是测试数据，实际使用请严格按照该格式返回
    /// </summary>

    public string sign { get; set; }
}